package com.baizhi.service.impl;

import com.baizhi.service.ThreadUserService;
import com.baizhi.service.UserService;
import com.baizhi.utils.ThreadPollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Map;

import java.util.concurrent.*;

/**
 * Created by 野马 on 2019/6/20.
 */
@Service
public class TreadUserServiceImpl implements ThreadUserService {

    @Autowired
    private UserService userService;


    @Override
    public Map getAllCountByFuture() throws Exception {

        //0  创建一个map封装数据
        Map map = new ConcurrentHashMap();
        //1创建连两个子线程  分别执行两个方法
        ThreadPoolExecutor executor = ThreadPollUtil.executor;
        //男女比例
        Future<Boolean> submit1 = executor.submit(new Callable<Boolean>() {


            @Override
            public Boolean call() throws Exception {
                List<Map> selectGroupBySex = userService.selectGroupBySex();
                map.put("Sex",selectGroupBySex);
                return true;
            }
        });
        //省份信息
        Future<Boolean> submit2 = executor.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                List<Map> selectGroupBySF = userService.selectGroupBySF();
                map.put("SF",selectGroupBySF);
                return true;
            }
        });
        //2 通过Future 效验子线程是否执行成功
        if(submit1.get() && submit2.get()){
            return map;
        }

        return map;
    }

    @Override
    public Map getAllCountByCountDownLatch() throws Exception {
        Map map = new ConcurrentHashMap();
        //1创建一个计数器
        CountDownLatch countDownLatch = new CountDownLatch(2);
        //2 创建线程  每个线程执行完计数器减一
        ThreadPoolExecutor executor = ThreadPollUtil.executor;
        //男女比例
        executor.submit(new Runnable() {
            @Override
            public void run() {
                List<Map> selectGroupBySex = userService.selectGroupBySex();
                map.put("Sex",selectGroupBySex);
                //计数器减一
                countDownLatch.countDown();
            }
        });
        //省份人数
        executor.submit(new Runnable() {
            @Override
            public void run() {
                List<Map> selectGroupBySF = userService.selectGroupBySF();
                map.put("SF",selectGroupBySF);
                countDownLatch.countDown();
            }
        });
        countDownLatch.await();


        return map;
    }
}
